#include "merge.hpp"

#include "qbe/src/ecs/app.hpp"

#include "qbe/src/ecs/query.hpp"

#include "qbe/src/axis/axis.hpp"
#include "qbe/src/input/input.hpp"
#include "qbe/src/select/select.hpp"
#include "qbe/src/state/state.hpp"
#include "qbe/src/undoRedo/undoRedo.hpp"
#include "qbe/src/utils/utils.hpp"

#include "qbe/src/layout/layout.hpp"

#include "qlib/all.h"

#include <QMessageBox>

namespace qbe::merge {

// 退出模式时回调
void exit_callback(ecs::Query query, state::AllModeType mode) {
  auto& move_param = query.get_resource<Models>();
  auto& layout_cmd = query.get_resource<layout::LayoutCmd>();
  auto& state = query.get_resource<state::State>();

  auto& cell = query.get_resource<qlib::Cell::s_ptr>();
  auto& reg = cell->reg;

  move_param.reset();
}

void init(ecs::Commands commands, ecs::Query query) {
  Models models;
  commands.insert_resource(models);

  auto& state = query.get_resource<state::State>();
  state.addExitCall(state::EditingModeType::Merge, exit_callback);
}

// 退出模式
void exit(ecs::Query query) {
  // 获取移动参数
  auto& move_param = query.get_resource<Models>();
  auto& layout_cmd = query.get_resource<layout::LayoutCmd>();

  // 获取reg
  auto& cell = query.get_resource<qlib::Cell::s_ptr>();
  auto& reg = cell->reg;

  // 退出模式
  auto& state = query.get_resource<state::State>();
  state.exit();

  move_param.reset();
}

// 获取鼠标当前点，需要考虑：吸附、斜角吸附
qlib::Vec2d getNowPoint(ecs::Query query) {
  auto& state = query.get_resource<state::State>();

  if (!state.isAdsorption()) {
    auto& axisModule = query.get_resource<axis::Axis>();
    qlib::Vec2d pos = {axisModule.real_x, axisModule.real_y};
    return pos;
  } else {
    return utils::getAdsorbedPoint(query);
  }
}

// 帧开始，模式转换
void stateTransformBegin(Models& models, state::State& state, input::HandleBundle* handle, ecs::Bus& bus, ecs::Query query) {
  if (models.state == State::None) {
    models.state = State::Complete;
  }
}

// 帧尾-退出模式
void stateTransformEnd(State& state) {}

template <typename T, typename... Args>
void getPolygon_impl(entt::registry& reg, entt::entity e, qlib::PolygonPtrArray& res, undoRedoT::UndoRedoModule& undoRedoModule,
                     layout::LayoutCmd& cmd) {
  auto ptr = reg.try_get<std::shared_ptr<T>>(e);

  if (ptr != nullptr) {
    if constexpr (std::is_same<T, qlib::Polygon>::value) {
      res.push_back(*ptr);
    } else if constexpr (std::is_same<T, qlib::Path>::value) {
      if ((*ptr)->width == 0) {
        return;
      }
      (*ptr)->to_polygons(false, {0, 0}, res);
    } else if constexpr (std::is_same<T, qlib::Label>::value) {
      auto polys_t = (*ptr)->to_polygons();
      res.insert(res.begin(), polys_t.begin(), polys_t.end());
    } else if constexpr (std::is_same<T, qlib::Text>::value) {
      auto polys_t = (*ptr)->to_polygons();
      res.insert(res.begin(), polys_t.begin(), polys_t.end());
    } else {
      qlib::Polygon::s_ptr polygon = (*ptr)->to_polygon();
      res.push_back(polygon);
    }

    undoRedoModule.dele(e);
    cmd.remove(e);

    return;
  }

  if constexpr (sizeof...(Args) > 0) {
    return getPolygon_impl<Args...>(reg, e, res, undoRedoModule, cmd);
  } else {
    // assert(0);
  }
}

#define QLIB_ELEMENT_MERGE_TYPE qlib::Polygon, qlib::Path, qlib::Rectangle, qlib::Ellipse, qlib::Fan, qlib::Pin

void getPolygon(entt::registry& reg, entt::entity e, qlib::PolygonPtrArray& res, undoRedoT::UndoRedoModule& undoRedoModule, layout::LayoutCmd& cmd) {
  getPolygon_impl<QLIB_ELEMENT_MERGE_TYPE>(reg, e, res, undoRedoModule, cmd);
}

// 移动逻辑
void update(ecs::Query query, ecs::Bus& bus) {
  // 判断编辑模式为移动
  auto& state = query.get_resource<state::State>();

  if (state.getEditingMode() != state::EditingModeType::Merge) {
    return;
  }

  // 获取cell和reg
  auto& cell = query.get_resource<qlib::Cell::s_ptr>();
  auto& reg = cell->reg;
  auto& layout_cmd = query.get_resource<layout::LayoutCmd>();

  // 获取输入 坐标系 撤销恢复
  auto& handModule = query.get_resource<vsg::ref_ptr<input::HandleBundle>>();
  auto& axisModule = query.get_resource<axis::Axis>();
  auto& undoRedoModule = query.get_resource<undoRedoT::UndoRedoModule>();

  // 获取移动参数
  auto& models = query.get_resource<Models>();

  stateTransformBegin(models, state, handModule, bus, query);

  if (models.state == State::Complete) {
    qlib::PolygonPtrArray merge_polygons;
    auto view = reg.view<select::SelectTag>();

    bool first = true;
    bool only_layer = true;

    view.each([&reg, &undoRedoModule, &layout_cmd, &models, &merge_polygons, &first, &only_layer](entt::entity e) {
      if (first) {
        models.layer = utils::getLayer(reg, e);
        first = false;
      } else {
        uint32_t layer = utils::getLayer(reg, e);
        if (layer != models.layer) {
          only_layer = false;
          return;
        }
      }
    });

    if (!only_layer) {
      QMessageBox::information(nullptr, QObject::tr("error"), QObject::tr("Unable to merge objects with different layers"));
      models.reset();
      state.exit();
      return;
    }

    undoRedoModule.start(cell);

    view.each([&reg, &undoRedoModule, &layout_cmd, &models, &merge_polygons, &first, &only_layer](entt::entity e) {
      getPolygon(reg, e, merge_polygons, undoRedoModule, layout_cmd);
    });

    qlib::PolygonPtrArray merge_res;
    qlib::ClipperTool::boolean(merge_polygons, qlib::PolygonPtrArray(), qlib::Operation::Or, 1.0, merge_res);

    for (auto poly : merge_res) {
      poly->layer = models.layer;
      auto e = layout_cmd.add(poly);
      reg.emplace_or_replace<select::SelectTag>(e);
      undoRedoModule.add(e);
    }

    undoRedoModule.end();

    auto& sele_event_writer = query.get_event_writer<select::Event>();
    sele_event_writer.send({select::Code::SelectUpdate});
    sele_event_writer.send({select::Code::HoverUpdate});

    models.reset();
    state.exit();
  }

  stateTransformEnd(models.state);
}

void Plugin::build(ecs::App& app) {
  app.add_stage<InitStage>();
  app.add_stage<UpdateStage>();

  app.add_systems<InitStage>(init);
  app.add_systems<UpdateStage>(update);
}

}  // namespace qbe::merge